﻿using System.Windows.Input;
using Bulb.Core.Services.CollectionService;
using Bulb.Core.Services.CollectionService.Messages;
using Bulb.Core.Services.DataStore;
using Cirrious.MvvmCross.Plugins.Messenger;
using Cirrious.MvvmCross.ViewModels;

namespace Bulb.Core.ViewModels
{
    public class DetailBulbViewModel : BaseViewModel
    {
        private BulbItem _item;
        
        private MvxSubscriptionToken _itemChangedSubscriptionToken;

        public DetailBulbViewModel(ICollectionService collectionService, IMvxMessenger messenger) : base(collectionService)
        {
            _itemChangedSubscriptionToken = messenger.Subscribe<ItemChangedMessage>(OnItemChanged);
        }

        private void OnItemChanged(ItemChangedMessage obj)
        {
            Update(Item.Id);
        }

        public class Nav
        {
            public int Id { get; set; }
        }

        public void Init(Nav navigation)
        {
            Update(navigation.Id);
        }

        public void Update(int id)
        {
            Item = CollectionService.Get(id);
        }

        public BulbItem Item
        {
            get { return _item; }
            set { _item = value; RaisePropertyChanged(() => Item); }
        }

        public ICommand EditDetailCommand
        {
            get { return new MvxCommand(() => ShowViewModel<EditBulbViewModel>(new EditBulbViewModel.Nav { Id = Item.Id })); }
        }

        public ICommand DeleteCommand
        {
            get
            {
                return new MvxCommand(() =>
                {
                    CollectionService.Delete(Item);
                    Close(this);
                });
            }
        }

        public ICommand OnCommand
        {
            get { return new MvxCommand(() => CollectionService.On(Item)); }
        }

        public ICommand OffCommand
        {
            get { return new MvxCommand(() => CollectionService.Off(Item)); }
        }
    }
}
